import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:raze/artifacts/auth_portal_dialog.dart';
import 'package:raze/artifacts/clickable_avatar_widget.dart';
import 'package:raze/artifacts/notifier_glimmer.dart';
import 'package:raze/artifacts/report_vault_dialog.dart';
import 'package:raze/lore/chronicle/qna_chronicle.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 问答详情页面
class KnowledgeDiscourseRealms extends StatefulWidget {
  const KnowledgeDiscourseRealms({super.key});

  @override
  State<KnowledgeDiscourseRealms> createState() =>
      _KnowledgeDiscourseRealmsState();
}

class _KnowledgeDiscourseRealmsState extends State<KnowledgeDiscourseRealms> {
  final TextEditingController _answerInputController = TextEditingController();
  final FocusNode _answerInputFocusNode = FocusNode();

  @override
  void dispose() {
    _answerInputController.dispose();
    _answerInputFocusNode.dispose();
    super.dispose();
  }

  /// 格式化时间为 HH:mm 格式
  String _formatTime(DateTime dateTime) {
    final hour = dateTime.hour.toString().padLeft(2, '0');
    final minute = dateTime.minute.toString().padLeft(2, '0');
    return '$hour:$minute';
  }

  @override
  Widget build(BuildContext context) {
    // 从路由参数获取问题ID
    final questionId = Get.parameters['questionId'] ?? '';
    final qnaChronicle = Get.find<QnAChronicle>();
    final userChronicle = Get.find<UserChronicle>();

    // 获取问题详情
    final question = qnaChronicle.queryQuestionById(questionId);
    if (question == null) {
      return Scaffold(
        backgroundColor: RazeConstants.background,
        body: Center(
          child:
              Text('Question not found')
                  .applyTypeSize(16.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyNotoSans(),
        ),
      );
    }

    return Scaffold(
      backgroundColor: RazeConstants.background,
      body: Column(
        children: [
          // 顶部导航栏
          _composeTopNavigationBar(questionId, qnaChronicle),

          // 问题和回答内容区域（可滚动）
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  16.h.boxHeight,

                  // 问题卡片
                  _assembleQuestionCard(
                    question: question,
                    qnaChronicle: qnaChronicle,
                    userChronicle: userChronicle,
                  ),
                  16.h.boxHeight,

                  // Answer 标题
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    child: Text('Answer')
                        .applyTypeSize(24.sp)
                        .applyTypeColor(RazeConstants.black)
                        .applyBagelFatOne(weight: FontWeight.w400),
                  ),
                  16.h.boxHeight,

                  // 回答列表
                  Obx(() {
                    final answers = qnaChronicle.fetchAnswersByQuestionId(
                      questionId,
                    );
                    if (answers.isEmpty) {
                      return Padding(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 32.h,
                        ),
                        child: Center(
                          child:
                              Text('No answers yet. Be the first to answer!')
                                  .applyTypeSize(14.sp)
                                  .applyTypeColor(
                                    RazeConstants.black.withOpacity(0.5),
                                  )
                                  .applyNotoSans(),
                        ),
                      );
                    }

                    return Column(
                      children:
                          answers.map((answer) {
                            final answerUser = userChronicle.queryUserById(
                              answer.userId,
                            );
                            return _constructAnswerCard(
                              answer: answer,
                              user: answerUser,
                            );
                          }).toList(),
                    );
                  }),

                  // 底部输入框占位空间
                  80.h.boxHeight,
                ],
              ),
            ),
          ),

          // 底部输入框
          _renderBottomInputBar(questionId, qnaChronicle, userChronicle),
        ],
      ),
    );
  }

  /// 组装顶部导航栏
  Widget _composeTopNavigationBar(
    String questionId,
    QnAChronicle qnaChronicle,
  ) {
    return Container(
      color: RazeConstants.background,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: SafeArea(
        bottom: false,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // 返回按钮
            Container(
                  width: 30.w,
                  height: 30.w,
                  decoration: BoxDecoration(
                    color: RazeConstants.background,
                    borderRadius: BorderRadius.circular(8.r),
                    border: Border.all(
                      color: RazeConstants.black,
                      width: 1.5.w,
                    ),
                  ),
                  child: Icon(
                    Icons.chevron_left_rounded,
                    size: 24.sp,
                    color: RazeConstants.black,
                  ),
                )
                .withRightBottomShadow(thickness: 1)
                .withTouchResonance(onTap: () => Get.back()),

            // 标题
            Text('Knowledge Q&A')
                .applyTypeSize(24.sp)
                .applyTypeColor(RazeConstants.black)
                .applyBagelFatOne(weight: FontWeight.w400),

            // 举报按钮
            Container(
                  width: 30.w,
                  height: 30.w,
                  decoration: BoxDecoration(
                    color: RazeConstants.background,
                    borderRadius: BorderRadius.circular(8.r),
                    border: Border.all(
                      color: RazeConstants.black,
                      width: 1.5.w,
                    ),
                  ),
                  padding: EdgeInsets.all(4.w),
                  child: Image.asset(
                    'assets/images/report2.png',
                    width: 20.w,
                    height: 20.w,
                  ),
                )
                .withRightBottomShadow(thickness: 1)
                .withTouchResonance(
                  onTap: () => _handleReportQuestion(questionId, qnaChronicle),
                ),
          ],
        ),
      ),
    );
  }

  /// 组装问题卡片
  Widget _assembleQuestionCard({
    required dynamic question,
    required QnAChronicle qnaChronicle,
    required UserChronicle userChronicle,
  }) {
    final user = userChronicle.queryUserById(question.userId);
    final timeStr = _formatTime(question.createTime);

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/question-background.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户信息行
          Row(
            children: [
              // 用户头像
              ClickableAvatarWidget(
                userId: user?.id ?? '',
                avatarPath: user?.avatar ?? 'assets/images/avatar1.png',
                width: 40.w,
                height: 40.w,
              ),
              12.w.boxWidth,
              // 用户名和时间
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      user?.username ?? 'Unknown',
                      style: TextStyle(
                        fontFamily:
                            GoogleFonts.openSans(
                              fontWeight: FontWeight.w700,
                            ).fontFamily,
                      ),
                    ).applyTypeSize(16.sp).applyTypeColor(RazeConstants.black),
                    4.h.boxHeight,
                    Text(timeStr)
                        .applyTypeSize(12.sp)
                        .applyTypeColor(RazeConstants.black.withOpacity(0.6))
                        .applyNotoSans(),
                  ],
                ),
              ),
              // 点赞按钮
              Obx(() {
                final currentUser = userChronicle.currentUser;
                final liked =
                    currentUser != null &&
                    qnaChronicle.checkQuestionLiked(
                      currentUser.id,
                      question.id,
                    );

                return GestureDetector(
                  onTap: () {
                    if (currentUser == null) {
                      AuthPortalDialog.revealAuthPortal();
                      return;
                    }

                    if (liked) {
                      qnaChronicle.unlikeQuestion(currentUser.id, question.id);
                    } else {
                      qnaChronicle.likeQuestion(currentUser.id, question.id);
                    }
                  },
                  child: Image.asset(
                    liked
                        ? 'assets/images/like.png'
                        : 'assets/images/unlike.png',
                    color: liked ? RazeConstants.red : RazeConstants.black,
                    width: 32.w,
                    height: 32.w,
                  ),
                );
              }),
            ],
          ),
          16.h.boxHeight,

          // 问题内容
          Text(
            question.content,
            style: TextStyle(
              fontFamily:
                  GoogleFonts.openSans(fontWeight: FontWeight.w600).fontFamily,
            ),
          ).applyTypeSize(16.sp).applyTypeColor(RazeConstants.black),
        ],
      ),
    );
  }

  /// 构建回答卡片
  Widget _constructAnswerCard({
    required dynamic answer,
    required dynamic user,
  }) {
    final timeStr = _formatTime(answer.createTime);

    return Container(
      margin: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 16.h),
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 9.h),
      decoration: BoxDecoration(
        color: RazeConstants.white,
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: RazeConstants.black, width: 1.w),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户信息行
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 用户头像
              ClickableAvatarWidget(
                userId: user?.id ?? '',
                avatarPath: user?.avatar ?? 'assets/images/avatar1.png',
                width: 40.w,
                height: 40.w,
              ),
              6.w.boxWidth,
              // 用户名和时间
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                          user?.username ?? 'Unknown',
                          style: TextStyle(
                            fontFamily:
                                GoogleFonts.openSans(
                                  fontWeight: FontWeight.w700,
                                ).fontFamily,
                          ),
                        )
                        .applyTypeSize(16.sp)
                        .applyTypeColor(RazeConstants.black)
                        .applyNotoSans(weight: FontWeight.w400),
                    2.h.boxHeight,
                    // 时间
                    Text(
                          timeStr,
                          style: TextStyle(
                            fontFamily:
                                GoogleFonts.openSans(
                                  fontWeight: FontWeight.w400,
                                ).fontFamily,
                          ),
                        )
                        .applyTypeSize(12.sp)
                        .applyTypeColor(RazeConstants.black.withOpacity(0.6))
                        .applyNotoSans(),
                  ],
                ),
              ),
              // 举报按钮
              GestureDetector(
                onTap: () => _triggerAnswerReport(answer.id),
                child: Image.asset(
                  'assets/images/report.png',
                  width: 20.w,
                  height: 20.w,
                ),
              ),
            ],
          ),
          6.h.boxHeight,

          // 回答内容
          Text(
                answer.content,
                style: TextStyle(
                  fontFamily:
                      GoogleFonts.openSans(
                        fontWeight: FontWeight.w400,
                      ).fontFamily,
                ),
              )
              .applyTypeSize(13.sp)
              .applyTypeColor(Colors.black.withValues(alpha: 0.70)),
        ],
      ),
    );
  }

  /// 渲染底部输入栏
  Widget _renderBottomInputBar(
    String questionId,
    QnAChronicle qnaChronicle,
    UserChronicle userChronicle,
  ) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        color: RazeConstants.background,
        border: Border(
          top: BorderSide(
            color: RazeConstants.black.withOpacity(0.1),
            width: 1,
          ),
        ),
      ),
      child: SafeArea(
        top: false,
        child: Container(
          padding: EdgeInsets.only(
            left: 16.w,
            right: 4.w,
            top: 4.h,
            bottom: 4.h,
          ),
          decoration: BoxDecoration(
            color: RazeConstants.white,
            borderRadius: BorderRadius.circular(16.r),
            border: Border.all(color: RazeConstants.black, width: 2.w),
          ),
          child: Row(
            children: [
              // 输入框
              Expanded(
                child: TextField(
                  controller: _answerInputController,
                  focusNode: _answerInputFocusNode,
                  decoration: InputDecoration(
                    hintText: 'Input Content',
                    hintStyle: TextStyle(
                      fontSize: 14.sp,
                      color: RazeConstants.black.withOpacity(0.4),
                      fontFamily: 'NotoSans',
                    ),
                    border: InputBorder.none,
                    isDense: true,
                    contentPadding: EdgeInsets.symmetric(vertical: 8.h),
                  ),
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: RazeConstants.black,
                    fontFamily: 'NotoSans',
                  ),
                  maxLines: 1,
                ),
              ),
              8.w.boxWidth,

              // 发送按钮（在输入框内部）
              Container(
                    width: 30.w,
                    height: 30.w,
                    decoration: BoxDecoration(
                      color: RazeConstants.yellow,
                      borderRadius: BorderRadius.circular(6.r),
                      border: Border.all(
                        color: RazeConstants.black,
                        width: 1.5.w,
                      ),
                    ),
                    child: Image.asset(
                      'assets/images/send.png',
                      width: 20.w,
                      height: 20.w,
                    ),
                  )
                  .withRightBottomShadow(thickness: 0.5)
                  .withTouchResonance(
                    onTap:
                        () => _executeSubmitAnswer(
                          questionId,
                          qnaChronicle,
                          userChronicle,
                        ),
                  ),
              6.w.boxWidth,
            ],
          ),
        ),
      ),
    );
  }

  /// 处理举报问题
  void _handleReportQuestion(String questionId, QnAChronicle qnaChronicle) {
    ReportVaultDialog.revealReportVault(
      onReportSubmitted: (_) {
        // 举报成功提示
        NotifierGlimmer.revealInfo('Report submitted successfully.');

        // 删除被举报的问题
        qnaChronicle.deleteQuestionById(questionId);

        // 返回上一页
        Get.back();
      },
    );
  }

  /// 触发举报回答流程
  void _triggerAnswerReport(String answerId) {
    final qnaChronicle = Get.find<QnAChronicle>();

    ReportVaultDialog.revealReportVault(
      onReportSubmitted: (_) {
        // 举报成功提示
        NotifierGlimmer.revealInfo('Report submitted successfully.');

        // 删除被举报的回答
        qnaChronicle.eraseAnswerById(answerId);
      },
    );
  }

  /// 执行提交回答
  void _executeSubmitAnswer(
    String questionId,
    QnAChronicle qnaChronicle,
    UserChronicle userChronicle,
  ) {
    // 检查是否登录
    if (!userChronicle.isLoggedIn) {
      AuthPortalDialog.revealAuthPortal();
      return;
    }

    // 获取输入内容
    final content = _answerInputController.text.trim();
    if (content.isEmpty) {
      NotifierGlimmer.revealInfo('Please enter your answer.');
      return;
    }

    // 提交回答
    final currentUser = userChronicle.currentUser!;
    qnaChronicle.submitAnswer(questionId, currentUser.id, content);

    // 清空输入框
    _answerInputController.clear();
    _answerInputFocusNode.unfocus();

    // 显示成功提示
    NotifierGlimmer.revealInfo('Answer submitted successfully!');
  }
}
